import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';
import 'package:ost_flutter_module/class/entity/store/shop_cart_entity.dart';
import 'package:ost_flutter_module/network/base_request_model.dart';
import 'package:ost_flutter_module/network/completable_action.dart';
import 'package:ost_flutter_module/network/http_manager.dart';
import 'package:ost_flutter_module/network/url_constants.dart';
import 'package:ost_flutter_module/widget/loading/loading_view.dart';
import 'package:uuid/uuid.dart';

import '../../../../main.dart';

part 'shop_cart_event.dart';
part 'shop_cart_state.dart';

class ShopCartBloc extends Bloc<ShopCartEvent, ShopCartState> {
  ShopCartBloc() : super(ShopCartInitial());

  BaseRequestListModel<ShopCartEntity> _dataModel =
      BaseRequestListModel<ShopCartEntity>();
  BaseRequestListModel<ShopCartEntity> get dataModel => _dataModel;

  @override
  Stream<ShopCartState> mapEventToState(
    ShopCartEvent event,
  ) async* {
    if (event is ShopCartFetchData) {
      yield* _mapFetchData(event, action: event.action);
    } else if (event is ShopCartEventOnCheck) {
    } else if (event is ShopCartEventOnApply) {
    } else if (event is ShopCartEventOnSubmit) {
      // yield* _mapOnSubmit(event);
    }
  }

  Stream<ShopCartFetchSuccess> _mapFetchData(
    ShopCartFetchData event, {
    CompletableAction action,
  }) async* {
    var result =
        await HttpManager.getInstance().syncRequestList<ShopCartEntity>(
      shop_cart,
      baseUrl: BASE_URL_MALL,
      method: Method.GET,
      params: null,
    );

    action?.completer?.complete(true);

    if (result.isSuccess) {
      logger.i(result.getOrNull);

      var list = result.getOrNull;
      _dataModel = _dataModel.copyWith(
        loadingStatus:
            (list.isEmpty) ? LoadingStatus.empty : LoadingStatus.success,
        dataList: list,
      );
    } else {
      logger.e(result.exceptionOrNull?.showMsg);
      _dataModel = _dataModel.copyWith(
        loadingStatus: LoadingStatus.error,
        dataList: null,
        isLastPage: false,
        errorMsg: result.exceptionOrNull?.showMsg,
      );
    }

    yield ShopCartFetchSuccess(Uuid().v4());
  }
}
